package com.masterclient.app.modules.shop;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.shop.adapter.StoreClassifyAdapter;
import com.masterclient.app.modules.shop.beans.SellerBean;
import com.masterclient.app.modules.shop.beans.StoreClassifyBean;
import com.masterclient.app.modules.shop.contract.StoreClassifyContract;
import com.masterclient.app.modules.shop.contract.StoreClassifyPresenter;
import com.masterclient.app.modules.shop.interfacess.SellerInfoCallback;
import com.masterclient.app.widget.FoldTextView;
import com.gyf.immersionbar.ImmersionBar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;


/**
 * @auther hjian
 * @date 2020/4/8.
 */
@Route(path = AroutePath.STORE_CLASSIFY_FRAGMENT)
public class StoreClassifyFragment extends BaseFragment<StoreClassifyPresenter> implements StoreClassifyContract.View {

    @BindView(R.id.store_classify_recycler)
    RecyclerView storeClassifyRecycler;
    @BindView(R.id.store_classify_refresh)
    SwipeRefreshLayout storeClassifyRefresh;
    @BindView(R.id.search_icon)
    ImageView searchIcon;
    @BindView(R.id.search_hint)
    TextView searchHint;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.search_back)
    ImageView searchBack;
    @BindView(R.id.search_framelayout)
    FrameLayout searchFramelayout;

    private String storeId;
    private StoreClassifyAdapter storeClassifyAdapter;
    private View headView;
    private ViewHolder viewHolder;
    private int scrollY;
    private SellerInfoCallback sellerInfoCallback;
    private FoldTextView.Callback foldCallback;

    public void setSellerInfoCallback(SellerInfoCallback sellerInfoCallback) {
        this.sellerInfoCallback = sellerInfoCallback;
    }


    public static StoreClassifyFragment getInstance(String store_id) {
        StoreClassifyFragment classifyFragment = new StoreClassifyFragment();
        Bundle bundle = new Bundle();
        bundle.putString("store_id", store_id);
        classifyFragment.setArguments(bundle);
        return classifyFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_store_classify, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).fitsSystemWindows(false).init();
        searchFramelayout.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);
        searchFramelayout.setBackgroundResource(R.color.transparent);

        storeId = getArguments().getString("store_id");

        headView = View.inflate(getActivity(), R.layout.head_store, null);
        viewHolder = new ViewHolder(headView);

        viewHolder.storePic.getLayoutParams().height = ImmersionBar.getStatusBarHeight(this)+ScreenUtils.dp2px(99);
        viewHolder.storeDesc.setEllipText("…");
        viewHolder.storeDesc.setEllipColor(0xff525866);
        foldCallback = new FoldTextView.Callback() {
            @Override
            public void onExpand() {
                viewHolder.storeMoreFl.setVisibility(View.VISIBLE);
                viewHolder.storeMoreIcon.setImageResource(R.mipmap.search_up);
            }

            @Override
            public void onCollapse() {
                viewHolder.storeMoreFl.setVisibility(View.VISIBLE);
                viewHolder.storeMoreIcon.setImageResource(R.mipmap.search_down);
            }

            @Override
            public void onLoss() {
                viewHolder.storeMoreFl.setVisibility(View.GONE);
            }
        };
        viewHolder.storeMoreLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.storeDesc.setChanged(!viewHolder.storeDesc.ismExpanded());
            }
        });

        storeClassifyAdapter = new StoreClassifyAdapter(storeId);
        storeClassifyRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        storeClassifyAdapter.setHeaderView(headView);
        storeClassifyAdapter.bindToRecyclerView(storeClassifyRecycler);
        storeClassifyRecycler.setAdapter(storeClassifyAdapter);

        refreshSellerInfo();

        viewHolder.storeCollected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.removeCollect(storeId);
            }
        });
        viewHolder.storeCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.collectShop(storeId);
            }
        });


        storeClassifyRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY += dy;

                float alph = scrollY * 1.0f / ScreenUtils.dp2px(100);
                if (scrollY >= ScreenUtils.dp2px(100)) alph = 1f;
                if (scrollY <= 7) alph = 0f;

                searchHint.setTextColor(alph > 0.3 ? 0xFF999FAA : 0xFFEDEFF2);
                searchBack.setImageResource(alph > 0.3 ? R.mipmap.back_black : R.mipmap.back_white);
                searchIcon.setImageResource(alph > 0.3 ? R.mipmap.icon_sousuo0 : R.mipmap.icon_sousuo);
                searchLl.setBackgroundResource(alph > 0.3 ? R.drawable.shape_store_search_bg_gray : R.drawable.shape_store_search_bg_white);
                searchFramelayout.setBackgroundColor(Color.argb((int) (255 * alph), 255, 255, 255));

            }
        });

        mPresenter.getStoreClassify(storeId);

        storeClassifyRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getStoreClassify(storeId);
            }
        });


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isVisible()) {
            refreshSellerInfo();
        }
    }

    private void refreshSellerInfo() {
        String favoriteState = ((StoreActivity) getActivity()).isFavorite;
        String onSaleTitle = ((StoreActivity) getActivity()).onSaleTitle;
        SellerBean data = ((StoreActivity) getActivity()).sellerBean;
        if (viewHolder == null) return;
        viewHolder.storeCollected.setVisibility("1".equals(favoriteState) ? View.VISIBLE : View.GONE);
        viewHolder.storeCollect.setVisibility("1".equals(favoriteState) ? View.GONE : View.VISIBLE);
        if (data != null) {
            if (!data.isIs_dealer()) {
                ViewTransformUtil.glideImageView(mContext, data.getBanner() , viewHolder.storePic,
                        new Transformation[]{new CenterCrop()}, R.mipmap.defaults_1);
                viewHolder.storeDealerIcon.setVisibility(View.GONE);
                viewHolder.storePicBg.setVisibility(View.VISIBLE);
            }else {
                viewHolder.storePic.setImageResource(R.mipmap.dealer_head_bg);
                viewHolder.storeCollect.setVisibility(View.GONE);
                viewHolder.storeCollected.setVisibility(View.GONE);
                viewHolder.storeDealerIcon.setVisibility(View.VISIBLE);
                viewHolder.storePicBg.setVisibility(View.GONE);
            }
            ViewTransformUtil.glideImageView(mContext, data.getLogo(), viewHolder.storeLogo, new Transformation[]{
                    new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(7), 0)}, R.mipmap.defaults);
            viewHolder.storeName.setText(data.getName());
            if (data.getShop_icon() != null && !TextUtils.isEmpty(data.getShop_icon().getBg_header_color())) {
                viewHolder.storeTagRecommendll.setVisibility(View.VISIBLE);
                int[] colors = {Color.parseColor(data.getShop_icon().getBg_header_color()),
                        Color.parseColor(data.getShop_icon().getBg_footer_color())};
                GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors);
                drawable.setCornerRadius(ScreenUtils.dp2px(2));
                drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
                viewHolder.storeTagRecommendll.setBackground(drawable);
                viewHolder.storeTagRecommend.setText(data.getShop_icon().getTitle());
                ViewTransformUtil.glideImageView(mContext, data.getShop_icon().getPre_icon(), viewHolder.storeTagRecommendicon,
                        new Transformation[]{new CenterCrop()}, R.mipmap.defaults_1);
            } else {
                viewHolder.storeTagRecommendll.setVisibility(View.GONE);
            }
            viewHolder.storeOnsale.setText(onSaleTitle);

            if (!TextUtils.isEmpty(data.getDesc())) {
                viewHolder.storeDesc.setText(data.getDesc(), false, foldCallback);
                viewHolder.storeDesc.setVisibility(View.VISIBLE);
            } else {
                viewHolder.storeDesc.setText("", false, foldCallback);
                viewHolder.storeDesc.setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.search_ll, R.id.search_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_ll:
                ARouter.getInstance().build(AroutePath.STORE_SEARCH_ACTIVITY).withBoolean("isSearch", true).withString("store_id", storeId).navigation();
                break;
            case R.id.search_back:
                getActivity().finish();
                break;
        }
    }

    @Override
    public void showData(StoreClassifyBean dataBean) {
        storeClassifyRefresh.setRefreshing(false);
        storeClassifyAdapter.setNewData(dataBean.getNavs());
    }

    @Override
    public void showDataFailed(String msg) {
        storeClassifyRefresh.setRefreshing(false);
        showToast(msg);
    }

    @Override
    public void collectSuccess(boolean isCollect) {
        viewHolder.storeCollected.setVisibility(isCollect ? View.VISIBLE : View.GONE);
        viewHolder.storeCollect.setVisibility(isCollect ? View.GONE : View.VISIBLE);
        sellerInfoCallback.onSellerInfo(isCollect ? "1" : "0", null, null);
        showToast(isCollect ? "关注成功" : "已取消关注");
    }

    class ViewHolder {
        @BindView(R.id.store_pic)
        ImageView storePic;
        @BindView(R.id.store_pic_bg)
        View storePicBg;
        @BindView(R.id.store_logo)
        ImageView storeLogo;
        @BindView(R.id.store_collected)
        LinearLayout storeCollected;
        @BindView(R.id.store_collect)
        TextView storeCollect;
        @BindView(R.id.store_collect_fl)
        FrameLayout storeCollectFl;
        @BindView(R.id.store_name)
        TextView storeName;
        @BindView(R.id.store_tag_recommendicon)
        ImageView storeTagRecommendicon;
        @BindView(R.id.store_tag_recommend)
        TextView storeTagRecommend;
        @BindView(R.id.store_tag_recommendll)
        LinearLayout storeTagRecommendll;
        @BindView(R.id.store_onsale)
        TextView storeOnsale;
        @BindView(R.id.store_dealer_icon)
        ImageView storeDealerIcon;
        @BindView(R.id.store_desc)
        FoldTextView storeDesc;
        @BindView(R.id.store_more_text)
        TextView storeMoreText;
        @BindView(R.id.store_more_icon)
        ImageView storeMoreIcon;
        @BindView(R.id.store_more_layout)
        LinearLayout storeMoreLayout;
        @BindView(R.id.store_more_fl)
        FrameLayout storeMoreFl;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
